package com.gxuwz.web.struts2;

import java.awt.image.BufferedImage;
import java.util.Hashtable;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.gxuwz.common.Const;
import com.gxuwz.common.MatrixToImageWriter;
import com.gxuwz.web.AbstractBaseController;

/**
 * 二维码控制器
 * @author 小胡  
 * @date 2017年5月28日
 */

public class QRCodeController extends AbstractBaseController implements
		ServletResponseAware {

	private static final long serialVersionUID = 243359089360628354L;
	private HttpServletResponse response;

	@Override
	public String execute() throws Exception {
		String text = "测试"; // 二维码内容

		Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, Const.DEFAULT_CODE); // 内容所使用字符集编码
		
		BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
				BarcodeFormat.QR_CODE, Const.QR_CODE_WIDTH,
				Const.QR_CODE_HEIGHT, hints);
		
		BufferedImage img = MatrixToImageWriter.toBufferedImage(bitMatrix);
		ImageIO.write(img, "gif", response.getOutputStream());
		return null;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

}
